import ToastComponent from './toast.vue'


var Toast = {}
Toast.install = function (Vue, options = {}) {
    // if (Toast.install) return;
    // console.log(Toast.install)
    // 默认值
    let opt = {
        type: 'center',
        duration: '1000'
    }
    if (options) Object.assign(opt, options)
    

    // Vue.component('Toast', Toast);
    let ToastController  = Vue.extend(ToastComponent)
    let removeDom = event => {
        if (event.target.parentNode.childNodes.length > 1) {
            event.target.parentNode.removeChild(event.target)
        } else {
            event.target.parentNode.parentNode.removeChild(event.target.parentNode)
        }   
    }

    ToastController.prototype.close = function () {
        this.visible = false
        this.$el.addEventListener('transitionend', removeDom)
    }

    Vue.prototype.$toast = (option = {}) => {
         var instance = new ToastController().$mount(document.createElement('div'));

         let duration = option.duration || opt.duration;

         instance.message = typeof option == 'string' ? option : option.message
         instance.type  = option.type || opt.type

         document.body.appendChild(instance.$el)
         instance.visible = true
         setTimeout(()=>{ instance.close() }, duration)

            
         return instance
    }
}
export default Toast;